In this notebook, a template is provided for you to implement your functionality in stages which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission, if necessary. Sections that begin with 'Implementation' in the header indicate where you should begin your implementation for your project. Note that some sections of implementation are optional, and will be marked with 'Optional' in the header.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
# Usual imports
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Load pickled data
import pickle
# Import Keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_dim_ordering('th')
# TODO: Fill this in based on where you saved the training and testing data
training_file = "./train.p"
testing_file = "./test.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_test, y_test = test['features'], test['labels']
# Load class descriptions
signnames = pd.read_csv("signnames.csv")
print("Data loaded...")
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 2D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below.
### Replace each question mark with the appropriate value.
# TODO: Number of training examples
n_train = len(X_train)
# TODO: Number of testing examples.
n_test = len(X_test)
# TODO: What's the shape of an traffic sign image?
image_shape = X_train.shape
# TODO: How many unique classes/labels there are in the dataset.
n_classes = max(y_train) + 1
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
# Display SignNames (class descriptions)
display(signnames)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
from scipy.misc import toimage
# Visualizations will be shown in the notebook.
%matplotlib inline
Let us visualize dataset by plotting an image from each class.
# show an image from each class in a grid
plt.subplots(figsize=(20, 35))
row = 1
col = 1
for i in range(n_classes):
class_id = np.where(y_train==i)[0][0]
plt.subplot2grid((10, 6), (row, col)) # we really need 9 x 5 = 45 to cover 43 images. Keep one extra each
plt.imshow(toimage(X_train[class_id]))
plt.axis("off")
title = signnames['SignName'][i]
plt.title(title)
col += 1
if(col > 5):
col = 1
row += 1
Let us plot histogram of training labels to visualize if there are any imbalances in class distribution
def show_samples_distribution():
plt.hist(y_train, n_classes)
plt.title('Number of samples per class')
plt.xlabel('Class')
plt.ylabel('Count')
_ = plt.show()
show_samples_distribution()
There is too much difference between the classes. We are going to create some data to balance the number of inputs and reduce the probable bias the network could have towards some classes. It will also help us give more data to our network.
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.
### Preprocess the data here.
### Feel free to use as many code cells as needed.
import cv2
print('Generating additional data...')
samples_per_class = np.bincount(y_train)
angles = [-3, 3, -5, 5, -10, 10, -15, 15, -20, 20]
image_cols = X_train.shape[1] # 32 x 32 image
image_rows = X_train.shape[2]
rotated_images = []
rotated_labels = []
# use openCV to rotate images of classes that have few samples
samples_count_in_max_class = max(samples_per_class)
for class_id in range(n_classes):
samples_count_in_this_class = samples_per_class[class_id]
shortfall = samples_count_in_max_class - samples_count_in_this_class
image_ids_in_this_class = np.where(y_train == class_id)[0]
for image_id in image_ids_in_this_class:
for angle in angles:
source_image = X_train[image_id]
rotation_matrix = cv2.getRotationMatrix2D((image_cols/2, image_rows/2), angle, 1)
rotated_image = cv2.warpAffine(source_image, rotation_matrix, (image_cols, image_rows))
rotated_images.append(rotated_image)
rotated_labels.append(class_id)
shortfall -= 1
if(shortfall <= 0): break
# plt.imshow(toimage(source_image))
# plt.imshow(toimage(rotated_image))
if(shortfall <= 0): break
print ("Finished rotating images")
# Concatenate generated data with loaded dataset
X_train = np.append(X_train, rotated_images, axis=0)
y_train = np.append(y_train, rotated_labels, axis=0)
# histogram with augumented data
show_samples_distribution()
# Normalize features from 0-255 to 0.0-1.0
X_train = X_train / 255.0
X_test = X_test / 255.0
print ("Finished normalizing images")
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
print ("Finished one hot encoding labels")
# Get randomized datasets for training and validation
from sklearn.model_selection import train_test_split
X_train, X_validation, y_train, y_validation = train_test_split(
X_train,
y_train,
test_size=0.2,
random_state=7
)
print('Finished randomizing and splitting dataset into train and validation')
Ah! The data looks more balanced now. Let us use it to train our Neural Network Classifier.
We will use a structure with two convolutional layers followed by max pooling and a flattening out of the network to fully connected layers to make predictions.
Our baseline network structure can be summarized as follows:
Fully connected output layer with 43 units and a softmax activation function.
A logarithmic loss function is used with the stochastic gradient descent optimization algorithm configured with a large momentum and weight decay start with a learning rate of 0.01.
# Create the model
model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(32, 32, 3), border_mode='same', activation='relu', W_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Convolution2D(32, 3, 3, activation='relu', border_mode='same', W_constraint=maxnorm(3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu', W_constraint=maxnorm(3)))
model.add(Dropout(0.5))
model.add(Dense(n_classes, activation='softmax'))
# Compile model
epochs = 25
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
print(model.summary())
We can fit this model with 25 epochs and a batch size of 32.
Once the model is fit, we evaluate it on the test dataset and print out the classification accuracy.
# Fit the model
history = model.fit(X_train, y_train, validation_data=(X_validation, y_validation), nb_epoch=epochs, batch_size=32)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
We can use the data collected in the history object to create plots.
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
Keras separates the concerns of saving your model architecture and saving your model weights.
Model weights are saved to HDF5 format. This is a grid format that is ideal for storing multi-dimensional arrays of numbers.
The model structure can be described and saved using two different formats: JSON and YAML.
# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model.h5")
print("Saved model to disk")
from keras.models import model_from_json
# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model.h5")
print("Loaded model from disk")
# evaluate loaded model on test data
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
loaded_model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
score = loaded_model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
predictions = loaded_model.predict(X_test)
import random
# show couple of random images from the given set
def plot_examples(preds, features, labels, show_errors=False):
# reverse one hot encoding
predicted_labels = np.argmax(np.round(preds), axis=1)
known_labels = np.argmax(labels, axis=1)
# compare model predictions with known labels
result = (predicted_labels == known_labels)
indices = [i for i, x in enumerate(result) if x == (not show_errors)]
# show an image from each class in a grid
plt.subplots(figsize=(20, 35))
for i in range(5):
image_id = random.choice(indices)
# image_id = indices[i]
plt.subplot(150 + 1 + i)
plt.imshow(toimage(features[image_id]))
label_id = predicted_labels[image_id]
predicted_title = signnames['SignName'][label_id]
label_id = known_labels[image_id]
known_title = signnames['SignName'][label_id]
plt.title("P: {}".format(predicted_title))
plt.xlabel("C: {}".format(known_title))
Let us look at couple of images for which our model got correct Predictions.
Text on the top of the images are the predicted labels, whereas text at the bottom of the imgaes are the true known labels.
plot_examples(predictions, X_test, y_test, False)
Let us also look at couple of images for which our model got predictions wrong.
plot_examples(predictions, X_test, y_test, True)
Describe how you preprocessed the data. Why did you choose that technique?
Answer:
I did some Exploratory Data Analysis before commencing. I plotted one image from each class to see what's in the dataset. I also loaded signnames.csv to understand the description of each class. Then I plotted histogram of the image samples by class. I noticed that many of the classes were under represented, which can cause poor performance of the Neural Net.
So I generated additional images in under represented classes by rotating images by small angles. OpenCV has a function, which does this with ease. Another plot of histogram shows that post-generation we have equal number of images in each class.
Then I normalized the values in images(features) from 0-255 to 0.0-1.0 so that variance in the data is low.
I then one-hot encoded the labels, because Neural Net model works well with this format for labels.
Finally, used sklearn's train_test_split function to randomize data and split dataset into training and validation set.
That's it. Our data is preprocessed and ready for ingestion into NN.
Describe how you set up the training, validation and testing data for your model. Optional: If you generated additional data, how did you generate the data? Why did you generate the data? What are the differences in the new dataset (with generated data) from the original dataset?
Answer:
I used sklearn's train_test_split function to randomize data and split dataset into training and validation set. I kept aside 20% of the training data for validations. I used test data only for final accuracy reporting of the model.
During Exploratory Data Analysis, I plotted histogram of the image samples by class. I noticed that many of the classes were under represented, which can cause poor performance of the Neural Net. So I generated additional images in under represented classes by rotating images by small angles. OpenCV has a function, which does this with ease. Another plot of histogram shows that post-generation we have equal number of images in each class.
What does your final architecture look like? (Type of model, layers, sizes, connectivity, etc.) For reference on how to build a deep neural network using TensorFlow, see Deep Neural Network in TensorFlow from the classroom.
Answer:
My Neural Network has two convolutional layers followed by max pooling and a flattening out of the network to fully connected layers to make predictions.
Network's structure can be summarized as follows:
Fully connected output layer with 43 units and a softmax activation function.
How did you train your model? (Type of optimizer, batch size, epochs, hyperparameters, etc.)
Answer:
To train the network, I used the logarithmic loss function with the stochastic gradient descent optimization algorithm configured with a large momentum and weight decay start with a learning rate of 0.01.
After many tests, and trial and errors, following parameters were used:
What approach did you take in coming up with a solution to this problem? It may have been a process of trial and error, in which case, outline the steps you took to get to the final solution and why you chose those steps. Perhaps your solution involved an already well known implementation or architecture. In this case, discuss why you think this is suitable for the current problem.
Answer:
Oh man! Where to begin. This project was full of trials and errors. I was playing with legos of Convolution blocks, Max Pooling blocks and Fully connected blocks.
I started small with few layers and nodes, and slowly built upon it. After some time, adding more convolution layers did not improve results, but increased computation time by a lot. So I scaled back. Besides, Traffic Sign images have low statistical invariance, so too many convolutions steps does not help.
In the end, I settled for a mid size architecture.
I did not use more than 25 epochs because validation accuracy was not improving after that.
Not to mention that I wanted to keep my AWS cost to minimum, so I called 92% test accuracy a success. Moreover, at this accuracy, model was able to correctly predict 5/6 images downloaded from internet. So, I was pretty happy.
Take several pictures of traffic signs that you find on the web or around you (at least five), and run them through your classifier on your computer to produce example results. The classifier might not recognize some local signs but it could prove interesting nonetheless.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
from os import listdir
import matplotlib.image as mpimg
images_folder = "images/"
new_images = []
# load new images from a folder
images = listdir(images_folder)
for image in images:
img = mpimg.imread(images_folder + image)
new_images.append(img)
# convert to numpy array, expected input type of the model
new_images = np.asarray(new_images)
# make predictions from the previously trained model
new_predictions = loaded_model.predict(new_images)
print("Prediction Confidence for respective images:")
print([max(i)*100 for i in np.round(new_predictions, 2)])
# reverse one hot encoding
new_label_ids = np.argmax(np.round(new_predictions), axis=1)
plt.subplots(figsize=(20, 35))
# plot new images with predicted labels on the top
for i, new_label_id in enumerate(new_label_ids):
predicted_title = signnames['SignName'][new_label_id]
plt.subplot(160 + 1 + i)
plt.imshow(new_images[i])
plt.axis("off")
plt.title(predicted_title)
Choose five candidate images of traffic signs and provide them in the report. Are there any particular qualities of the image(s) that might make classification difficult? It could be helpful to plot the images in the notebook.
Answer:
I downloaed the above 6 images from the internet. Then used GIMP to crop and scale images to desired 32x32 size. I then fed these new images to the previously trained model. The predictions for each image is shown on the top of the images.
Most of the images that I found were copy right protected. These images are of very bad quality (pixelated), and would make classification not easy for the model. I also noticed that the one image that my model got wrong, has background and foreground color pretty similar. Could this have caused an issue in our small-ish network?
In the end, 5/6 images were correctly classified. So it looks like we trained our network well :)
Is your model able to perform equally well on captured pictures when compared to testing on the dataset? The simplest way to do this check the accuracy of the predictions. For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate.
NOTE: You could check the accuracy manually by using signnames.csv (same directory). This file has a mapping from the class id (0-42) to the corresponding sign name. So, you could take the class id the model outputs, lookup the name in signnames.csv and see if it matches the sign from the image.
Answer:
Model correctly classified 5 out of 6 internet images. Thus resulting in 83.33% accuracy. I have plotted all the internet images above with predicted class labels on the top.
I'm not quite sure, why it got the 6th image wrong. I also noticed that this image has background and foreground color pretty similar. Not a huge contrast for the sign to standout. Could this have caused an issue in our small-ish network?
Model generalizes well with the data from the dataset. Correctly recognizing 5 images from the internet is nothing short of a magic to me. :)
Use the model's softmax probabilities to visualize the certainty of its predictions, tf.nn.top_k could prove helpful here. Which predictions is the model certain of? Uncertain? If the model was incorrect in its initial prediction, does the correct prediction appear in the top k? (k should be 5 at most)
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
Answer:
Following is the Prediction Confidence for each internet images: [73.000001907348633, 100.0, 97.000002861022949, 100.0, 100.0, 100.0]
Model correctly classified 5 out of 6 images. The model is pretty certain of all the images that it got correct. For "Speed limit (80km/hr)", "No Entry", and "Stop" it was 100% certain. For other two, "Speed limit (20km/hr)" and "General caution", model's certainity was less than 100%, but still highest.
The last image - "Left Turn", is most perplexing output. Model is 100% sure that it is a "Roundabout" sign, which is 100% wrong! I'm not quite sure, how to explain this. Time permitting I intend to investigate this further with bigger networks.
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.